/*
 * Copyright Aristool AG Switzerland
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package org.opprua.dss.application;

import org.opprua.dss.data.Result;
import org.opprua.tidy.beans.BeanHandler;
import org.opprua.tidy.util.XReader;
import org.w3c.dom.Element;

/**
 * TODO: add Java doc
 * 
 * Prepared for first commit: 23.02.2007
 * 
 * @author Lin Li
 */
public class DDataPoint extends XReader {

  private DCall[] calls;
  private Class<? extends Object> rType;

  @Override
  public void read(Element e) {
    calls = collect(e, "call", DCall.class);
  }

  public void registerCalls(DApplication app) {
    for (int i = 0; i < calls.length; i++) {
      calls[i].setParamType(null);
      calls[i].setReturnType(getTypeName());
      calls[i].register(app);
    }
  }

  public String getName() {
    return getAttribute("name");
  }

  public String getTypeName() {
    return getAttribute("type");
  }

  public Class<? extends Object> getType() {
    if (rType == null) {
      String n = getTypeName();
      if (RUtil.isType(n)) {
        rType = RUtil.getScriptable(n);
      } else {
        rType = Object.class;
      }
    }
    if (rType.equals(Object.class)) return null;
    return rType;
  }

  public DCall[] getCall() {
    return calls;
  }

  public Result<?> execute() {
    for (int i = 0; i < calls.length; i++) {
      Result<?> r = calls[i].call(null);
      if (r != null && r.getType() == Result.TYPE.SUCCESS) { return r; }
    }

    if (rType == null) {
      return Result.success(null);
    }

    try {
      return Result.success((Object) BeanHandler.fake(rType));
    } catch (Exception e) {
      return Result.failure("Application exception", e.getMessage());
    }
  }
}